package com.db.bytebuffer.service;

import java.nio.ByteBuffer;

public class IntegerMapPrinter {
    private ByteBuffer byteBuffer;

    private static final int FIELDS_COUNT = 3;
    private static final int INTEGER_SIZE_BYTES = 4;

    public IntegerMapPrinter(ByteBuffer byteBuffer) {
        this.byteBuffer = byteBuffer;
    }

    public void print() {
        System.out.println("Printing Integer Map");
        for (int i = 0; i < byteBufferLimit(); i += FIELDS_COUNT) {
            if (getKey(i) != Integer.MIN_VALUE) {
                System.out.printf("%d [%d=>%d]", i, getKey(i), getValue(i));
                if (getLink(i) != Integer.MIN_VALUE) {
                    System.out.printf(" %d", getLink(i));
                }
                System.out.printf("\n");
            }
        }
        System.out.println();
    }

    private int byteBufferLimit() {
        return byteBuffer.limit() / INTEGER_SIZE_BYTES;
    }

    private int getKey(int i) {
        return byteBuffer.getInt(i * INTEGER_SIZE_BYTES);
    }

    private int getValue(int i) {
        return byteBuffer.getInt((i + 1) * INTEGER_SIZE_BYTES);
    }

    private int getLink(int i) {
        return byteBuffer.getInt((i + 2) * INTEGER_SIZE_BYTES);
    }
}
